//
//  DrugSearchViewController.m
//  pocketmedicine
//
//  Created by student on 16/4/22.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "DrugSearchViewController.h"
#import "DrugShowController.h"
#import "MedicineModel.h"
#import  <SVProgressHUD.h>
@interface DrugSearchViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITextField *idTextField;

@property (strong, nonatomic) IBOutlet UITableView *tableViewList;




@property (strong,nonatomic) NSArray *arr;
@property (strong,nonatomic) NSMutableArray *listarr;
@property (strong,nonatomic) NSMutableArray *drugList;
@end



@implementation DrugSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableViewList.delegate = self;
    self.tableViewList.dataSource = self;
    self.tableViewList.hidden = YES;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)cancel:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [SVProgressHUD dismiss];
}

- (IBAction)btnPressed:(id)sender
{
    [self.idTextField resignFirstResponder];
    NSString *httpUrl = @"http://www.tngou.net/api/search";
    NSString *httpArg = [NSString stringWithFormat:@"name=drug&keyword=%@",self.idTextField.text];
    httpArg = [httpArg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//转换网址中的中文字符
    
    [self request: httpUrl withHttpArg: httpArg];
    
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.idTextField resignFirstResponder];
}

-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    
     [SVProgressHUD showWithStatus:@"正在搜索"];
    // 网址字符串
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    // 网址
    NSURL *url = [NSURL URLWithString: urlStr];
    // 请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    // GET请求
    [request setHTTPMethod: @"GET"];
    // 设置请求头
    [request addValue: @"639a5ad1fd83cbabd5b467f9201a5c8c" forHTTPHeaderField: @"apikey"];
    
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                                   [SVProgressHUD showWithStatus:@"搜索错误"];
                                   self.tableViewList.hidden = YES;
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                                      NSLog(@"HttpResponseCode:%ld", responseCode);
                                                                      NSLog(@"HttpResponseBody %@",responseString);
                                   
                                   NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                   self.arr = [dict objectForKey:@"tngou"];
                                   
                                                                      //初始化成员变量
                                   _listarr = [[NSMutableArray alloc]init];
                                   self.drugList = [[NSMutableArray alloc] init];
                                   
                                   for (int i = 0; i<self.arr.count; i++) {
                                       
                                       //按数组中的索引取出对应的字典
                                       NSDictionary *listdic = [self.arr objectAtIndex:i];
                                       
                                        self.medicine = [[MedicineModel alloc] initWithDict:listdic];
                                       
//                                       if (listdic!=nil) {
//                                           [SVProgressHUD dismiss];}


                                       //通过字典中的key取出对应value，并且强制转化为NSString类型
                                       NSString *teamname = (NSString *)[listdic objectForKey:@"name"];
                                       
                                       //将获取的value值放到数组容器中
                                       [_listarr addObject:teamname];
                                       [self.drugList addObject:self.medicine];
                                       


                                   }
                                   
                                   [self.tableViewList reloadData];
                                   
                               }
                               if (self.medicine.name!=nil) {
                                   self.tableViewList.hidden = NO;
                                   [SVProgressHUD dismiss];
                                   
                               }else {
                                   self.tableViewList.hidden = YES;
                                   [SVProgressHUD showWithStatus:@"搜索错误"];
                               }
                               

                              
                           }];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listarr.count;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:( NSIndexPath *)indexPath
{
    
    

    DrugShowController *dc = [self.storyboard instantiateViewControllerWithIdentifier:@"ShowVC"];
    [SVProgressHUD showWithStatus:@"正在加载"];
    [self presentViewController:dc animated:YES completion:nil];
    
    dc.medicine = self.drugList[indexPath.row];
    
    if (dc.medicine!=nil) {
        [SVProgressHUD dismiss];}
    
   
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    cell.textLabel.text = [_listarr objectAtIndex:indexPath.row];
   
    return cell;
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
